﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WAF.Server.Ipc;
using WAF.Server;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace PerformanceTests
{
    public class WebServerService : WebServerCore,  IAppServerIpcCallbackContract
    {
        PerformanceTestBase performanceTest;
        IAppServerIpcContract channel;

        public WebServerService(PerformanceTestBase performanceTest, bool useNamedPipes)
        {
            this.performanceTest = performanceTest;
            Init(SendAppServerRequest, ProcessNativeResponse);

            Console.WriteLine("Create Channel");
            try
            {

                Binding binding;
                EndpointAddress endpoint;

                if (useNamedPipes)
                {
                    endpoint = new EndpointAddress("net.pipe://localhost/2WAF/PerformanceTests");
                    NetNamedPipeBinding pipesBinding = new NetNamedPipeBinding();
                    pipesBinding.TransferMode = TransferMode.Buffered;
                    pipesBinding.Security.Mode = NetNamedPipeSecurityMode.None;
                    binding = pipesBinding;
                }
                else
                {
                    endpoint = new EndpointAddress("net.tcp://localhost/2WAF/PerformanceTests");
                    NetTcpBinding tcpBinding = new NetTcpBinding();
                    tcpBinding.TransferMode = TransferMode.Buffered;
                    tcpBinding.Security.Mode = SecurityMode.None;
                    binding = tcpBinding;
                }

                DuplexChannelFactory<IAppServerIpcContract> factory = new DuplexChannelFactory<IAppServerIpcContract>(this, binding, endpoint);
                channel = factory.CreateChannel();
                Console.WriteLine("Channel Created - try to establish");
                channel.AddServer(this.WebServerID);
                Console.WriteLine("Channel Established");

            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to Create/Establish Buffered TCP Channel");
                Console.WriteLine(e.ToString());
                Console.WriteLine();
            }

        }

        public void AppServerResponse(ContentResponse response)
        {
            ProcessAppServerResponse(response);
        }

        public void SendAppServerRequest(ContentRequest request)
        {
            channel.ProcessRequest(request);
        }

        public void ProcessNativeResponse(ContentResponse response, object nativeContext)
        {
            performanceTest.RecceiveResponse(response);
        }

    }
}
